﻿using System;
using System.Threading.Tasks;
using LeoGemini.Service.Infrastructure.Handler.Exception;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace LeoGemini.Service.Infrastructure.Handler.Filter
{
    public class HttpExceptionFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<HttpExceptionFilter> _logger;
        
        public HttpExceptionFilter(ILogger<HttpExceptionFilter> logger)
        {
            _logger = logger;
        }
        
        public Task OnExceptionAsync(ExceptionContext context)
        {
            var httpContext = context.HttpContext;
            if (!context.ExceptionHandled)
            {
                if (context.Exception is HttpException httpException)
                {
                    context.Result = new ContentResult
                    {
                        StatusCode = httpException.HttpStatusCode,
                        ContentType = "application/json;charset=utf-8",
                        Content = JsonConvert.SerializeObject(new
                        {
                            Code = httpException.HttpStatusCode,
                            httpException.Message,
                            Data = new
                            {
                                Time = DateTime.Now, httpContext.Request.Path
                            }
                        }, new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        })
                    };
                    context.ExceptionHandled = true;
                }
            }

            return Task.CompletedTask;
        }
    }
}